<template>
	<view class="chat" :style="{height: style.contentViewHeight + 'px'}">
		<scroll-view id="scrollview" class="content" scroll-y="true" :style="{height: style.contentViewHeight + 'px'}" :scroll-with-animation="true" enable-back-to-top="true" show-scrollbar="true" :scroll-into-view="scrollInto" upper-threshold="50" @scrolltoupper="historyRecord(false)">
			<view class="item" v-for="(item, i) of list" :key="i" :id="'s'+i">
				<view class="chat-time">{{item.msgTime}}</view>
				<view class="chat-item" :class="item.from">
					<!-- <image class="chat-avatar" :src="item.avatar" @click="goUserHome(item.user_id)"></image> -->
					<u-avatar class="chat-avatar" :src="item.avatar" size="80" @click="goUserHome(item.user_id)"></u-avatar>
					<view class="chat-text" v-if="item.media == 1">{{item.content}}</view>
					<image class="chat-emoji" v-if="item.media == 6" mode="aspectFit" :src="item.src"></image>
					<image class="chat-image" @click="getImgIndex(i)" v-if="item.media == 4" mode="widthFix" :src="item.src"></image>
				</view>
			</view>
			<!-- <view class="item">
				<view class="chat-time">11月14日 14:23</view>
				<view class="chat-item right">
					<image class="chat-avatar" src="../../static/image/test.png"></image>
					<view class="chat-audio"><m-audio direction="right" src='../../static/audio/test.mp3'></m-audio></view>
				</view>
			</view>-->
		</scroll-view>

		<!-- 底部菜单 -->
		<view style="height: 100rpx" >
			<view class="bottom" v-click-outside="closeBottomDialog">
				<!-- 菜单 -->
				<view class="input">
					<image class="leftImg" v-if="bottom.voiceShow" @click="inputFocus" src="../../../static/image/Chat/键盘@3x.png"></image>
					<image class="leftImg" v-else @click="showVoice" src="../../../static/image/Chat/语音@2x.png"></image>
					<view class="bgColor">
						<view class="inputView">
							<textarea
								class="inputText"
								v-model="bottom.inputText"
								:focus="bottom.inputFocusFlag"
								@focus="inputFocus"
								@blur="inputBlur"
								:auto-height="true"
								:cursor-spacing="12"
								:maxlength="1200"
								:fixed="true"
								:show-confirm-bar="false"
							/>
						</view>

						<image class="emoji" v-if="bottom.isEmojiOpen" @click="inputFocus" src="../../../static/image/Chat/键盘@3x.png"></image>
						<image class="emoji" v-else @click="showEmoji" src="../../../static/image/Chat/表情@2x.png"></image>
					</view>
					<view v-if="bottom.inputText" class="sendBtn" @click="sendText">发送</view>
					<image v-else class="rightImg" @click="showMore" src="../../../static/image/Chat/添加@2x.png"></image>
				</view>

				<!-- 底部弹窗 -->
				<voice-btn v-if="bottom.voiceShow" @handleEvent="handleEvent"></voice-btn>
				<emoji-btn v-if="bottom.isEmojiOpen" @handleEvent="handleEvent"></emoji-btn>
				<more-btn v-if="bottom.moreShow" @handleEvent="handleEvent"></more-btn>
				<!-- 底部弹窗end -->
			</view>
		</view>
		<!-- 底部菜单end -->
	</view>
</template>

<script>
import VoiceBtn from '../components/VoiceBtn.vue'
import EmojiBtn from '../components/EmojiBtn.vue'
import MoreBtn from '../components/MoreBtn.vue'

import { emojiMap, emojiUrl } from '@/utils/emojiMap'
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
	components: {
		VoiceBtn,
		EmojiBtn,
		MoreBtn
	},
	mounted() {
		// this.setHeight();
	},
	data() {
		return {
			bottom: {
				voiceShow: false,
				inputFocusFlag: false,
				inputText: '',
				isEmojiOpen: false,
				moreShow: false,
			},
			userId: 0,
			token: '',
			userAvatar: '../../../static/logo.png',
			dstId: 0,
			dstAvatar: '../../../static/logo.png',
			memberList: [],
			list: [],
			emojiMap: emojiMap,
			emojiUrl: emojiUrl,
			scrollInto: "",
			// 聊天页面时时滚动样式
			style: {
				oldContentViewHeight: 0,
				contentViewHeight: 0
			},
			basicMsg: {
				cmd: 11
			},
			page: 0,
			isEnd: false
		};
	},
	computed: {
		...mapGetters(['isLogin']),
		...mapState(['loginInfo', 'userInfo'])
	},
	created() {
		if (!this.isLogin) {
			this.$u.route({
				url: 'pages/auth/login/login',
				type: 'reLaunch'
			})
			return
		}
	},
	methods: {
		recvMsg(reData) {
			this.formatMessage(JSON.parse(reData), true, true)
		},
		async sendMsg(message) {
			message.created_at = this.$utils.getDateNow()
			message.count = 0
			const res = await this.$ws.sendMessage(message)
		},
		// 预览图片
		getImgIndex(index){
			// 准备一个装图片路径的  数组imgs
			var imgs = []
			var imgLen = 0
			var cur = 0
			for(var i=0, len=this.list.length; i<len; i++) {
				if (this.list[i].media == 4) {
					imgLen += 1
					imgs.push(this.list[i].pic)
					if (index == i) {
						cur = imgLen - 1
					}
				}
			}
			//调用预览图片的方法
			uni.previewImage({
				urls:imgs,
				current: cur
			})
		},
		formatMessage(message, isScrollInto, isPush) {
			if (message.user_id == this.userId) {
				message.from = 'right'
				message.avatar = this.userAvatar
			} else {
				message.from = 'left'
				if (this.memberList[message.user_id]) {
					message.avatar = this.memberList[message.user_id].avatar
				}
			}
			message.msgTime = this.$utils.formatDate(message.created_at)
			if (message.media == 4) {
				message.src = message.thumb_pic
			}
			if (message.media == 6) {
				message.src = this.emojiUrl + this.emojiMap[message.content]
			}
			if (isPush) {
				this.list.push(message)
			} else {
				this.list.unshift(message)
			}
			if (isScrollInto == true) {
				this.scrollToBottom()
			}
		},
		changeScrollHeight() {
			this.style.contentViewHeight = this.style.oldContentViewHeight
			this.style.contentViewHeight -= 150;
			this.scrollToBottom()
		},
		scrollToBottom: function () {
			var len = this.list.length
			if (len >= 1) {
				len = len - 1
			}
			setTimeout(() => {
				this.scrollInto = 's' + len
			}, 1);
		},
		goUserHome(userId) {
			this.$u.route('/pages/addressBook/userHome/userHome', {
				userId: userId
			})
		},
		// 底部弹窗关闭，语音和更多的弹窗
		closeBottomDialog() {
			this.bottom.voiceShow = false
			this.bottom.isEmojiOpen = false
			this.bottom.moreShow = false
			this.style.contentViewHeight = this.style.oldContentViewHeight
		},
		// 开语音弹窗，关闭其他弹窗
		showVoice() {
			this.closeBottomDialog()
			this.bottom.voiceShow = true
			this.changeScrollHeight()
		},
		// 开emoji弹窗，关闭其他弹窗
		showEmoji() {
			this.closeBottomDialog()
			this.bottom.isEmojiOpen = true
			this.changeScrollHeight()
		},
		showMore() {
			this.closeBottomDialog()
			this.bottom.moreShow = true
			this.changeScrollHeight()
		},
		// 输入框得到焦点
		inputFocus(e) {
			this.closeBottomDialog();
			this.bottom.inputFocusFlag = true;
		},
		// 输入框失去焦点
		inputBlur() {
			this.bottom.inputFocusFlag = false;
		},
		createMsgContext:function(){
			return JSON.parse(JSON.stringify(this.basicMsg))
		},
		sendText() {
			let message = this.createMsgContext()
			message.media = 1
			message.content = this.bottom.inputText
			this.sendMsg(message)
			message.created_at = ''
			this.formatMessage(message, true, true)
			this.bottom.inputText = ''
		},
		sendEmoji(emoji) {
			let message = this.createMsgContext()
			message.media = 6
			message.content = emoji
			this.sendMsg(message)
			message.created_at = ''
			this.formatMessage(message, true, true)
			this.closeBottomDialog();
		},
		sendImage(picUrl) {
			let message = this.createMsgContext()
			message.media = 4
			message.thumb_pic = picUrl[0]
			message.pic = picUrl[1]
			message.content = 'image'
			this.sendMsg(message)
			message.created_at = ''
			this.formatMessage(message, true, true)
		},
		selectImage() {
			uni.chooseImage({
				count: 1,
				sourceType: ['album', 'camera'],
				sizeType: ['original', 'compressed'],
				extension: ['jpg','png','jpeg','gif'],
				success: (chooseImageRes) => {
					uni.showLoading({
					    title: '发送图片中...'
					});
					const tempFilePaths = chooseImageRes.tempFilePaths;
					uni.uploadFile({
						url: this.$config.domain + '/v1/attach/upload', //仅为示例，非真实的接口地址
						header: {Authorization: "Bearer " + this.token},
						filePath: tempFilePaths[0],
						name: 'file',
						success: (uploadFileRes) => {
							uni.hideLoading();
							var res = JSON.parse(uploadFileRes.data)
							if (res.status_code == 200) {
								this.sendImage(res.data)
							} else {
								this.$u.toast(res.message)
							}
						}
					});
				}
			});
		},
		handleEvent(event, data) {
			switch (event) {
				case 'voice':
					break;
				case 'emoji':
					this.sendEmoji(data)
					break;
				case 'image':
					this.selectImage()
					break;
			}
		},
		async historyRecord(isInit) {
			if (!this.isEnd) {
				this.page += 1
				let res = await this.$u.api.historyRecord({dstId:this.dstId, cmd:this.basicMsg.cmd, page:this.page})
				if (res != '') {
					var oldLen = this.list.length
					var len = res.data.length
					console.log("page="+this.page+" historyRecord="+len)
					if (len < 20) {
						this.isEnd = true
					}
					for (var i = 0; i < len; i++) {
						this.formatMessage(res.data[i], false, false)
					}
					if (isInit) {
						// 请求后端，将消息都设成已读
						this.makeMessageRead()
						setTimeout(() => {
							this.scrollInto = 's' + (len - 1)
						}, 1);
					} else {
						setTimeout(() => {
							this.scrollInto = 's' + len
						}, 1);
					}
				}
			} else {
				console.log("到底了！")
			}
		},
		async makeMessageRead() {
			let res = await this.$u.api.makeMessageRead({dstId:this.dstId, cmd:this.basicMsg.cmd})
		},
		async getMemberList() {
			let res = await this.$u.api.memberList({dstId:this.dstId})
			if (res != '') {
				var len = res.data.length
				for (var i = 0; i < len; i++) {
					this.memberList[res.data[i].id] = res.data[i]
				}
				console.log(this.memberList)
			}
		},
		async getUserInfo(userId) {
			let res = await this.$u.api.userInfo({userId: userId})
			if (res != '') {
				this.memberList[res.data.id] = res.data
				return res.data.avatar
			}
			return '../../../static/logo.png'
		},
	},
	onNavigationBarButtonTap() {  
		this.$u.route('/pages/addressBook/groupHome/groupHome', {
			dstId: this.dstId
		})
	},
	async onLoad(options) {
		uni.setNavigationBarTitle({
			title: options.name
		})
		this.dstId = parseInt(options.dstId)
		// 群聊里的成员
		this.getMemberList()
		
		this.userId = this.userInfo.id
		this.token = this.loginInfo.token
		this.userAvatar = this.userInfo.avatar
		
		this.historyRecord(true)
		this.basicMsg = {
			cmd: 11,
			user_id: this.userId,
			dst_id: this.dstId
		}
		
		const res = uni.getSystemInfoSync()   // 获取手机可使用窗口高度     api为获取系统信息同步接口
		this.style.contentViewHeight = res.windowHeight - 50 // 像素
		this.style.oldContentViewHeight = this.style.contentViewHeight
	}
};
</script>

<style lang="scss" scoped>
page {
	background: #f4f4f4;
}
.chat {
	.content {
		.item {
			padding: 0 20rpx;
			
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				padding: 40rpx 0;
				text-align: center;
			}

			.left {
				flex-direction: row;
				.chat-avatar {
					margin-right: 16rpx;
				}
				.chat-text {
					background: #ffffff;
					border-radius: 0 20rpx 20rpx 20rpx;
					padding: 16rpx 22rpx 16rpx 24rpx;
				}
			}

			.right {
				flex-direction: row-reverse;
				.chat-avatar {
					margin-left: 16rpx;
				}
				.chat-text {
					background: #ffe431;
					border-radius: 20rpx 0 20rpx 20rpx;
					padding: 16rpx 24rpx 16rpx 22rpx;
				}
			}

			.chat-item {
				display: flex;
				.chat-avatar {
					background: #ffe431;
					border-radius: 20rpx;
				}

				.chat-text {
					max-width: 480rpx;
					font-size: 32rpx;
					color: #272832;
				}

				.chat-image {
					border-radius: 20rpx;
					width: 284rpx;
				}
				
				.chat-emoji {
					width: 112rpx;
					height: 112rpx;
				}
			}
		}
	}

	.bottom {
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 999;
		background-color: #fff;
		.input {
			display: flex;
			align-items: center;
			padding: 14rpx 22rpx;

			.leftImg {
				width: 50rpx;
				height: 50rpx;
			}

			.rightImg {
				width: 50rpx;
				height: 50rpx;
				margin-left: 18rpx;
			}

			.bgColor {
				flex: 1;
				min-height: 70rpx;
				background-color: #f0f0f0;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				padding: 10rpx 15rpx 10rpx 29rpx;
				margin-left: 10rpx;

				.inputView {
					flex: 1;
					margin-right: 10rpx;
					.inputText {
						max-height: 200rpx;
						width: 100%;
						font-size: 30rpx;
						font-weight: 400;
						color: #333333;
						line-height: 45rpx;
						opacity: 0.4;
					}
				}

				.emoji {
					width: 50rpx;
					height: 50rpx;
				}
			}

			.sendBtn {
				margin-left: 10rpx;
				width: 98rpx;
				height: 60rpx;
				background: #d6a662;
				border-radius: 10rpx;
				font-size: 30rpx;
				font-weight: 500;
				color: #ffffff;
				text-align: center;
				line-height: 60rpx;
			}

			.sendBtn:active {
				background-color: rgba($color: #d6a662, $alpha: 0.8);
			}
		}
	}
}
</style>